package com.ssttevee.taskmanagerapp;

import java.util.ArrayList;
import java.util.List;

import net.robotmedia.billing.BillingController;
import net.robotmedia.billing.BillingRequest.ResponseCode;
import net.robotmedia.billing.helper.AbstractBillingObserver;
import net.robotmedia.billing.model.Transaction;
import net.robotmedia.billing.model.Transaction.PurchaseState;

import com.ssttevee.taskmanagerapp.R;
import com.ssttevee.taskmanagerapp.adapter.TaskListAdapter;
import com.ssttevee.taskmanagerapp.services.RefreshServers;
import com.ssttevee.taskmanagerapp.tasks.AppRater;
import com.ssttevee.taskmanagerapp.tasks.ServerCommunicator;
import com.ssttevee.taskmanagerapp.tasks.Task;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ViewAnimator;

public class ViewServersActivity extends Activity {
	
	private ResponseReceiver receiver;
	private TaskManagerApplication app;
	private TaskListAdapter adapter;
	private TextView addButton;
	private AlertDialog testDialog;
	private boolean isServerNotified;
	private boolean unlockMsgSeen;
	private boolean isPurchased = false;
	private int selectedServerPos;
	private Button viewButton;
	private Typeface tf;
	private RelativeLayout mainView;
	private RelativeLayout splash;
	private Button refreshButton;
	private Button deleteButton;
	private Button editButton;
	private ListView lv;
	private AlertDialog deleteServerDialog;
	private AbstractBillingObserver mBillingObserver;
	private SharedPreferences prefs;
	private ViewAnimator va;
	public RelativeLayout header;
	public TextView headerTitle;
	public LinearLayout ll1;
	public LinearLayout ll2;
	public ImageView bottom_shadow;
	public ImageView bottom_bg;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		viewSetup();
		setContentView(va);
		
		SudoMethod sm = new SudoMethod("something");
		sm.execute("");

		app = (TaskManagerApplication) getApplication();
		adapter = new TaskListAdapter(app.getCurrentTasks(), ViewServersActivity.this);
	}

	protected void onRequestPurchaseResponse(String itemId, ResponseCode response) {
		
	}

	protected void onBillingChecked(boolean supported) {
		if (supported) {
			restoreTransactions();
		} else {
			Toast.makeText(getBaseContext(), "Can't Make Purchase", Toast.LENGTH_SHORT).show();
		}
		
	}
	private void restoreTransactions() {
		if (!mBillingObserver.isTransactionsRestored()) {
			BillingController.restoreTransactions(this);
		}
	}

	private void unlockedSetup() {
		Intent intent = new Intent("com.ssttevee.taskmanagerapp.services.PeriodicPoll");
		startService(intent);
	}

	protected void onPurchaseStateChanged(String itemId, PurchaseState state) {
		checkUpgradeStatus();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
		this.unregisterReceiver(receiver);
	}

	@Override
	public void onResume() {
		super.onResume();
		selectedServerPos = -1;
		app.loadTasks();
		adapter.setTasks(app.getCurrentTasks());
		adapter.keepSelected(selectedServerPos);
		adapter.forceReload();
		if(viewButton != null) {
			viewButton.setEnabled(false);
			editButton.setEnabled(false);
			deleteButton.setEnabled(false);
		}
		
		IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
		filter.addCategory(Intent.CATEGORY_DEFAULT);
		receiver = new ResponseReceiver();
		registerReceiver(receiver, filter);
	}

	private void viewSetup() {
		splash = new RelativeLayout(ViewServersActivity.this);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
		splash.setLayoutParams(params);
		splash.setId(R.id.splash_screen);
		splash.setBackgroundDrawable(getResources().getDrawable(R.drawable.newui_background));
		
		mainView = new RelativeLayout(ViewServersActivity.this);
		mainView.setLayoutParams(params);
		mainView.setId(R.id.main_ui);
		mainView.setBackgroundDrawable(getResources().getDrawable(R.drawable.newui_background));
		
		ImageView splashImg = new ImageView(ViewServersActivity.this);
		splashImg.setLayoutParams(params);
		splashImg.setScaleType(ScaleType.CENTER_INSIDE);
		splashImg.setImageDrawable(getResources().getDrawable(R.drawable.splash));
		
		splash.addView(splashImg);

		va = new ViewAnimator(this);
		va.setInAnimation(inFromLeftAnimation());
		va.setOutAnimation(outToRightAnimation());
		va.addView(splash, 0);
		va.addView(mainView, 1);
	}
	
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
		} else if(keyCode == KeyEvent.KEYCODE_BACK) {
		}
		return super.onKeyUp(keyCode, event);
	}
	
	protected void addServerButtonOnClickHandler() {
		Intent intent = new Intent(this, AddServerActivity.class);
		intent.putExtra("id", (long) 65535);
		intent.putExtra("name", "");
		intent.putExtra("host", ":25565");
		intent.putExtra("motd", "");
		intent.putExtra("max_players", 0);
		intent.putExtra("online_players", 0);
		intent.putExtra("players", "");
		intent.putExtra("latency", 0);
		intent.putExtra("gs4_port", 0);
		intent.putExtra("version", "");
		intent.putExtra("times_online", 0);
		intent.putExtra("times_checked", 0);
		intent.putExtra("online", false);
		startActivity(intent);
		overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
	}
	
	protected void viewServerButtonOnClickHandler() {
		if(selectedServerPos >= 0) {
			Task t = adapter.getItem(selectedServerPos);
			app.setCurrentTask(t);
			
			Intent intent = new Intent(this, ViewInfoActivity.class);
			intent.putExtra("id", t.getId());
			startActivity(intent);
		}
	}

	protected void sendPopup(String msg) {
		testDialog = new AlertDialog.Builder(this)
			.setTitle(R.string.unsaved_changed_title)
			.setMessage(msg)
			.setPositiveButton(R.string.add_task, new AlertDialog.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
				}
			})
			.setNeutralButton(R.string.discard, new AlertDialog.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			})
			.setNegativeButton(R.string.cancel, new AlertDialog.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					testDialog.cancel();
				}
			}).create();
		testDialog.show();
	}
	
	private void checkUpgradeStatus() {
        SharedPreferences.Editor prefsEditor = prefs.edit();
		
		if(isServerNotified || unlockMsgSeen) {
			isPurchased = true;
		}
		
		List<Transaction> transactions = BillingController.getTransactions(this);
		for (Transaction t : transactions) {
			if (t.purchaseState == PurchaseState.PURCHASED) {
				if(t.productId == "com.ssttevee.taskmanagerapp.upgrade") {
					isPurchased = true;
					if(!isServerNotified) {
						(new ServerCommunicator(this)).storeUpgradedDevice(t);
				        prefsEditor.putString("UNLOCKED", "true");
						prefsEditor.commit();
					}
				}
			}
		}
		if(!isPurchased) {
			isPurchased = (new ServerCommunicator(this)).checkLicence("com.ssttevee.taskmanagerapp.upgrade");
		}
		if(isPurchased && !unlockMsgSeen) {
			testDialog = new AlertDialog.Builder(this)
				.setTitle("Hurrah!")
				.setMessage("You have successfully upgraded McLister!  This upgrade should follow you to all your devices, ")
				.setNeutralButton("OK", new AlertDialog.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
				        SharedPreferences.Editor prefsEditor = prefs.edit();
				        prefsEditor.putString("UNLOCK_MSG_SEEN", "true");
						prefsEditor.commit();
					}
				}).create();
			testDialog.show();
		}
	}
	
	public boolean isInternetAvavilable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
		return activeNetworkInfo != null;
	}
	
	public class ResponseReceiver extends BroadcastReceiver {
		public static final String ACTION_RESP = "com.ssttevee.intent.action.SERVER_POLLED";
				
		@Override
		public void onReceive(Context context, Intent intent) {
			int[] i = intent.getIntArrayExtra(RefreshServers.RETURNING_MESSAGE);
			app.loadTasks();
			adapter.setTasks(app.getCurrentTasks());
			adapter.endPoll(i[0]);
		}
	}

	private Animation inFromLeftAnimation() {
		Animation inFromLeft = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, +1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromLeft.setDuration(500);
		inFromLeft.setInterpolator(new AccelerateInterpolator());
		return inFromLeft;
	}

	private Animation outToRightAnimation() {
		Animation outtoRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, -1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		outtoRight.setDuration(500);
		outtoRight.setInterpolator(new AccelerateInterpolator());
		return outtoRight;
	}

	private class SudoMethod extends AsyncTask<String, String, String> {
		long time;

		public SudoMethod(String str) {
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			time = System.currentTimeMillis() + 2500;
		}
		
		@Override
		protected String doInBackground(String... strings) {
			
			header = new RelativeLayout(ViewServersActivity.this);
			RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, getResources().getDimensionPixelSize(R.dimen.header_full_height));
			params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
			header.setLayoutParams(params);
			header.setId(R.id.header);
			header.setBackgroundDrawable(getResources().getDrawable(R.drawable.header_bar));
			
			headerTitle = new TextView(ViewServersActivity.this);
			params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, getResources().getDimensionPixelSize(R.dimen.header_real_height));
			params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
			headerTitle.setLayoutParams(params);
			headerTitle.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
			headerTitle.setText("McLister");
			headerTitle.setTextSize(26);
			headerTitle.setTextColor(Color.rgb(255, 255, 255));
			
			ll1 = new LinearLayout(ViewServersActivity.this);
			params = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
			ll1.setLayoutParams(params);
			ll1.setId(R.id.bottom_btns);
			
			editButton = new Button(ViewServersActivity.this);
			LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT, 0.5f);
			lparams.setMargins(3, 3, 3, 3);
			editButton.setLayoutParams(lparams);
			editButton.setText("Edit");
			editButton.setTextColor(Color.rgb(255, 255, 255));
			editButton.setTextSize(15);
			editButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.mc_btn));
			
			deleteButton = new Button(ViewServersActivity.this);
			lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT, 0.5f);
			lparams.setMargins(3, 3, 3, 3);
			deleteButton.setLayoutParams(lparams);
			deleteButton.setText("Delete");
			deleteButton.setTextColor(Color.rgb(255, 255, 255));
			deleteButton.setTextSize(15);
			deleteButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.mc_btn));
			
			refreshButton = new Button(ViewServersActivity.this);
			lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT, 0.5f);
			lparams.setMargins(3, 3, 3, 3);
			refreshButton.setLayoutParams(lparams);
			refreshButton.setText("Refresh");
			refreshButton.setTextColor(Color.rgb(255, 255, 255));
			refreshButton.setTextSize(15);
			refreshButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.mc_btn));

			ll2 = new LinearLayout(ViewServersActivity.this);
			params = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			params.addRule(RelativeLayout.ABOVE, ll1.getId());
			ll2.setLayoutParams(params);
			ll2.setId(R.id.add_task_btn);
			
			viewButton = new Button(ViewServersActivity.this);
			lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT, 0.5f);
			lparams.setMargins(3, 3, 3, 3);
			viewButton.setLayoutParams(lparams);
			viewButton.setText("More Info");
			viewButton.setTextColor(Color.rgb(255, 255, 255));
			viewButton.setTextSize(15);
			viewButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.mc_btn));
			
			addButton = new Button(ViewServersActivity.this);
			lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT, 0.5f);
			lparams.setMargins(3, 3, 3, 3);
			addButton.setLayoutParams(lparams);
			addButton.setText("Add Server");
			addButton.setTextColor(Color.rgb(255, 255, 255));
			addButton.setTextSize(15);
			addButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.mc_btn));
			
			lv = new ListView(ViewServersActivity.this);
			params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
			params.addRule(RelativeLayout.ABOVE, ll2.getId());
			params.addRule(RelativeLayout.BELOW, header.getId());
			params.setMargins(0, getResources().getDimensionPixelSize(R.dimen.header_real_height) * -1, 0, 0);
			lv.setLayoutParams(params);
			lv.setCacheColorHint(Color.TRANSPARENT);
			
			bottom_bg = new ImageView(ViewServersActivity.this);
			params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
			params.addRule(RelativeLayout.ALIGN_TOP, ll2.getId());
			params.addRule(RelativeLayout.ALIGN_BOTTOM, ll1.getId());
			bottom_bg.setLayoutParams(params);
			bottom_bg.setScaleType(ScaleType.FIT_XY);
			bottom_bg.setImageDrawable(getResources().getDrawable(R.drawable.newui_bottom));
			
			bottom_shadow = new ImageView(ViewServersActivity.this);
			params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, getResources().getDimensionPixelSize(R.dimen.header_real_height));
			params.addRule(RelativeLayout.ABOVE, ll2.getId());
			bottom_shadow.setLayoutParams(params);
			bottom_shadow.setScaleType(ScaleType.FIT_XY);
			bottom_shadow.setImageDrawable(getResources().getDrawable(R.drawable.newui_bshadow));
			
			tf = Typeface.createFromAsset(getAssets(), "fonts/volter.ttf");
			prefs = ViewServersActivity.this.getSharedPreferences("mclprefs", MODE_PRIVATE);
			isServerNotified = Boolean.parseBoolean(prefs.getString("SERVER_NOTIFIED", "false"));
			unlockMsgSeen = Boolean.parseBoolean(prefs.getString("UNLOCK_MSG_SEEN", "false"));
			
			checkUpgradeStatus();
			publishProgress("1");

			if(isPurchased) {
				unlockedSetup();
			}

			addButton.setTypeface(tf);
			viewButton.setTypeface(tf);
			viewButton.setEnabled(false);
			editButton.setTypeface(tf);
			editButton.setEnabled(false);
			deleteButton.setTypeface(tf);
			deleteButton.setEnabled(false);
			refreshButton.setTypeface(tf);
			addButton.setOnClickListener( new View.OnClickListener() {
				public void onClick(View v) {
					if(isInternetAvavilable()) {
						addServerButtonOnClickHandler();
					} else {
						Toast.makeText(getBaseContext(), "Network Unavailable", Toast.LENGTH_SHORT).show();
					}
				}
			});
			deleteButton.setOnClickListener( new View.OnClickListener() {
				public void onClick(View v) {

					Task t = adapter.getItem(selectedServerPos);
					deleteServerDialog = new AlertDialog.Builder(ViewServersActivity.this)
					.setTitle("Confirm Delete")
					.setMessage("Are you sure you want to delete " + t.getName() + "?  All data collected from this server will be lost.")
					.setNeutralButton("I'm Sure!", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Task t = adapter.getItem(selectedServerPos);
							app = (TaskManagerApplication) getApplication();
							app.delTasks(t.getId());
							Toast.makeText(getBaseContext(), t.getName() + " deleted", Toast.LENGTH_SHORT).show();
							app.loadTasks();
							adapter.setTasks(app.getCurrentTasks());
							adapter.forceReload();

							selectedServerPos = -1;
							adapter.keepSelected(selectedServerPos);
							viewButton.setEnabled(false);
							editButton.setEnabled(false);
							deleteButton.setEnabled(false);
						}
					})
					.setNegativeButton("No", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							deleteServerDialog.cancel();
						}
					}).create();
				deleteServerDialog.show();
				}
			});
			editButton.setOnClickListener( new View.OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(ViewServersActivity.this, AddServerActivity.class);
					Task t = adapter.getItem(selectedServerPos);
					intent.putExtra("id", t.getId());
					intent.putExtra("name", t.getName());
					intent.putExtra("host", t.getHost());
					intent.putExtra("motd", t.getMotd());
					intent.putExtra("max_players", t.getMaxPlayers());
					intent.putExtra("online_players", t.getOnlinePlayers());
					intent.putExtra("players", t.getPlayers());
					intent.putExtra("latency", t.getLatency());
					intent.putExtra("gs4_port", t.getGs4Port());
					intent.putExtra("version", t.getVersion());
					intent.putExtra("times_online", t.getTimesOnline());
					intent.putExtra("times_checked", t.getTimesChecked());
					intent.putExtra("online", t.isOnline());
					startActivity(intent);
				}
			});
			refreshButton.setOnClickListener( new View.OnClickListener() {
				public void onClick(View v) {
					if(isInternetAvavilable()) {
						ArrayList<Task> at = adapter.getTasks();
						int i = 0;
						for(Task t : at) {
							Intent msgIntent = new Intent("com.ssttevee.taskmanagerapp.services.RefreshServers");
							msgIntent.putExtra(RefreshServers.GETTING_MESSAGE, new int[]{i, (int) t.getId()});
							startService(msgIntent);
							i++;
						}
						adapter.startPoll();
					} else {
						Toast.makeText(getBaseContext(), "Network Unavailable", Toast.LENGTH_SHORT).show();
					}
				}
			});
			viewButton.setOnClickListener( new View.OnClickListener() {
				public void onClick(View v) {
					viewServerButtonOnClickHandler();
				}
			});
			lv.setOnItemClickListener( new OnItemClickListener() {

				public void onItemClick(AdapterView<?> arg0, View v, int pos, long id) {
					if(selectedServerPos == (int) id) {
						viewServerButtonOnClickHandler();
					} else {
						selectedServerPos = (int) id;
						adapter.keepSelected(selectedServerPos);
						viewButton.setEnabled(true);
						editButton.setEnabled(true);
						deleteButton.setEnabled(true);
					}
				}
			});
			
			adapter.setFont(Typeface.createFromAsset(getAssets(), "fonts/volter.ttf"));
			lv.setAdapter(adapter);
			
			// SudoMethod sm = new SudoMethod();
			// sm.execute();

			mBillingObserver = new AbstractBillingObserver(ViewServersActivity.this) {

				public void onBillingChecked(boolean supported) {
					ViewServersActivity.this.onBillingChecked(supported);
				}

				public void onPurchaseStateChanged(String itemId, PurchaseState state) {
					ViewServersActivity.this.onPurchaseStateChanged(itemId, state);
				}

				public void onRequestPurchaseResponse(String itemId, ResponseCode response) {
					ViewServersActivity.this.onRequestPurchaseResponse(itemId, response);
				}
			};
			
			BillingController.registerObserver(mBillingObserver);
			BillingController.checkBillingSupported(ViewServersActivity.this);
			
			AppRater.app_launched(ViewServersActivity.this);
			return "All Done!";
		}
		
		@Override
		protected void onProgressUpdate(String... values) {
			if(values[0] == "0") {
			} else if(values[0] == "1") {
				mainView.addView(header);
				header.addView(headerTitle);
				mainView.addView(bottom_bg);
				mainView.addView(bottom_shadow);
				mainView.addView(ll1);
				ll1.addView(editButton);
				ll1.addView(deleteButton);
				ll1.addView(refreshButton);
				mainView.addView(ll2);
				ll2.addView(viewButton);
				ll2.addView(addButton);
				mainView.addView(lv);
			}
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			long nowTime = System.currentTimeMillis();
			if(nowTime < time) {
				try {
					Thread.sleep(time - nowTime) ;
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					Log.i("ViewServersActivity", "View Changed");
					va.setDisplayedChild(1);
				}
			} else {
				Log.i("ViewServersActivity", "View Changed");
				va.setDisplayedChild(1);
			}
		}
	}
}
